package br.com.educa.modelo.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.PersistenceContext;
import javax.persistence.Version;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.serializable.RooSerializable;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

import br.com.educa.util.CollectionUtils;
import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

@Configurable
@Entity
@RooJavaBean
@RooSerializable
@RooToString
@RooJpaActiveRecord
@RooJson
public class Menu implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Version
    @Column(name = "version")
    private Integer version;

    private Integer ordem;

    @ManyToOne
    private Menu pai;
    
    @OneToMany(mappedBy="pai")
    @OrderBy("ordem")
    private Set<Menu> filhos;

    private String url;

    private String nome;
    
    @PersistenceContext
    transient EntityManager entityManager;

    private static final long serialVersionUID = 1L;

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Integer getVersion() {
        return this.version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

    public static final EntityManager entityManager() {
        EntityManager em = new Menu().entityManager;
        if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)");
        return em;
    }

    public static long countMenus() {
        return entityManager().createQuery("SELECT COUNT(o) FROM Menu o", Long.class).getSingleResult();
    }

    public static List<br.com.educa.modelo.security.Menu> findAllMenus() {
        return entityManager().createQuery("SELECT o FROM Menu o order by o.pai.id, o.ordem", Menu.class).getResultList();
    }

    public static br.com.educa.modelo.security.Menu findMenu(Long id) {
        if (id == null) return null;
        return entityManager().find(Menu.class, id);
    }

    public static List<br.com.educa.modelo.security.Menu> findMenuEntries(int firstResult, int maxResults) {
        return entityManager().createQuery("SELECT o FROM Menu o", Menu.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
    }

    @Transactional
    public void persist() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.persist(this);
    }

    @Transactional
    public void remove() {
        if (this.entityManager == null) this.entityManager = entityManager();
        if (this.entityManager.contains(this)) {
            this.entityManager.remove(this);
        } else {
            Menu attached = Menu.findMenu(this.id);
            this.entityManager.remove(attached);
        }
    }

    @Transactional
    public void flush() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.flush();
    }

    @Transactional
    public void clear() {
        if (this.entityManager == null) this.entityManager = entityManager();
        this.entityManager.clear();
    }

    @Transactional
    public br.com.educa.modelo.security.Menu merge() {
        if (this.entityManager == null) this.entityManager = entityManager();
        Menu merged = this.entityManager.merge(this);
        this.entityManager.flush();
        return merged;
    }

    public Integer getOrdem() {
        return this.ordem;
    }

    public void setOrdem(Integer ordem) {
        this.ordem = ordem;
    }

    public br.com.educa.modelo.security.Menu getPai() {
        return this.pai;
    }

    public void setPai(br.com.educa.modelo.security.Menu pai) {
        this.pai = pai;
    }

    public String getUrl() {
        return this.url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getNome() {
        return this.nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

	public String toJson() {
        return new JSONSerializer().exclude("filhos").exclude("*.class").serialize(this);
    }

	public static Menu fromJsonToMenu(String json) {
        return new JSONDeserializer<Menu>().use(null, Menu.class).deserialize(json);
    }

	public static String toJsonArray(Collection<Menu> collection) {
        return new JSONSerializer().exclude("filhos").exclude("*.class").serialize(collection);
    }

	public static Collection<Menu> fromJsonArrayToMenus(String json) {
        return new JSONDeserializer<List<Menu>>().use(null, ArrayList.class).use("values", Menu.class).deserialize(json);
    }

	public List<Menu> getFilhos() {
		List<Menu> retorno = new CollectionUtils<Menu>().toArrayList(filhos);
		Collections.sort (retorno, new Comparator<Menu>() {
				public int compare(Menu o1, Menu o2) {
								 return o1.getOrdem().compareTo(o2.getOrdem());
				}
		});
		return retorno;
	}

	public void setFilhos(Set<Menu> filhos) {
		this.filhos = filhos;
	}

	
	
}
